<template>
  <div class="add">
    <el-dialog :title="title" :before-close="closeCall" :visible.sync="addDialog" append-to-body width="90%" top="50px">
      <div class="body">
        <el-steps :active="activeIndex" align-center>
          <el-step title="查看基本信息" ></el-step>
          <el-step title="查看接口用例" ></el-step>
        </el-steps>

        <!--第一步-->
        <transition name="show">
          <div class="body-item edit" v-show="activeIndex === 1">
            <el-form :model="dataForm" label-width="140px" size="mini" :disabled="disabled">
              <el-form-item label="集成测试名称" prop="name" :rules="{ required: true, message: '请输入集成测试名称' }">
                <el-input v-model="dataForm.name" placeholder="请输入集成测试名称" maxlength="20"></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="remark" :rules="{ max:200,message: '最多200个字节' }">
                <el-input type="textarea" v-model="dataForm.remark" placeholder="请输入备注" :rows="5"></el-input>
              </el-form-item>
              <el-form-item >
                <task-plan-set ref="plan" :execute-plan-data="executePlanData" :disabled="disabled"/>
              </el-form-item>
            </el-form>
          </div>
        </transition>

        <!--第三步-->
        <transition name="show">
          <div class="body-item border-item" v-show="activeIndex === 3">
            <el-row class="height">
              <el-col :span="12" class="height">
                <el-row class="height">
                  <el-col :span="12" class="height">
                    <div class="interface-bar">
                      <div class="interface-div">
                        <div class="title">接口名称</div>
                        <interface-list-chk :interface-data="interfaceData" @clickRowCall="clickInterfaceCall" :view="viewDialog"/>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12" class="height">
                    <div class="use-case-bar">
                      <div class="title">测试用例
                        <!--<el-button type="danger" size="mini" class="fr" @click="deleteUseCase">批量删除</el-button>
                        <el-button type="primary" size="mini" class="fr" @click="onClickQuote" style="margin-right: 10px">引用</el-button>-->
                      </div>
                      <test-use-case-list-chk :use-list="useCase" @selectionChange="selectionChange" @rowClickTestUse="rowClickTestUse"/>
                    </div>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="12" class="height">
                <div class="interface-config-bar">
                  <div class="interface-config">
                    <interface-config v-if="isInterfaceConfig" disabled :node="node" />
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </transition>

      </div>


      <div class="btn-bar">
        <el-button v-if="activeIndex > 1" type="primary" size="mini" @click="activeIndex = 1">上一步</el-button>
        <el-button v-if="activeIndex === 1" type="primary" size="mini" @click="next">下一步</el-button>
      </div>

      <el-dialog title="接口详情" :visible.sync="isDetails" append-to-body width="90%">
        <interface-details :node="node" v-if="isDetails"/>
      </el-dialog>

      <CaseList v-if="isUseCase" ref="caseList"
                @useListCall="useListCall"
                @closeCaseCall="closeCaseCall"
                :history-list="useCaseList"
                :type="2"
                :dialogVisibleCase="isUseCase"
                :node="node"/>
    </el-dialog>
  </div>
</template>

<script>

  import TaskPlanSet from "./TaskPlanSet"
  import TestTools from '@/rdComponent/common/testTools'
  import ServiceList from '@/rdComponent/common/ServiceList'
  import InterfaceDetails from "@/rdComponent/common/InterfaceDetails";
  import SelectUseCase from './SelectUseCase'
  import InterfaceList from './InterfaceList';
  import InterfaceListChk from './InterfaceListChk';
  import TestUseCaseList from './TestUseCaseList';
  import TestUseCaseListChk from './TestUseCaseListChk';
  import CaseList from '../../useCase/component/CaseList'
  import InterfaceConfig from "@/rdComponent/common/InterfaceConfig";
  export default {
    components: {
      InterfaceConfig,
      InterfaceDetails, InterfaceList, TestUseCaseList,TestUseCaseListChk,InterfaceListChk,
      TaskPlanSet, TestTools, ServiceList, SelectUseCase, CaseList
    },
    name: "Add",
    props: {
      confDialog: {
        type: Boolean,
        default: false
      },
      //判断0：添加，1：修改，2详情
      type: {
        type: Number,
        default: 0
      },
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      detail: {
        type: Object,
        required: false
      }
    },
    data() {
      return {
        viewDialog: false,
        addDialog: this.confDialog,
        detailDialog: false,
        activeIndex: 1,
        dataForm: {
          name: "",
          remark: "",
        },

        isTestTools: true,
        sId: "",
        icons: [
          {
            name: "添加",
            isIcon: true,
            iconName: "el-icon-plus",
            btnIndex: 1,
          },
          {
            name: "查看",
            isIcon: true,
            iconName: "el-icon-document",
            btnIndex: 2,
          }
        ],
        interfaceData: [],
        node: {},
        isDetails: false,
        isUseCase: false,
        isInterfaceConfig: false,
        useCase: [],
        useCaseList: [],
        executePlanData: {},
        multipleSelection: [],
        title: "配置详情",
      }
    },
    created() {
      let that = this;
      switch (this.type) {
        case 0: this.title = "新增集成与性能测试"; break;
        case 1: this.title = "修改集成与性能测试"; break;
        default: this.title = "查看配置详情"; break;
      }
      if (Object.keys(this.detail).length > 0) {
        console.log("detail: ", this.detail);
        //填充数据
        this.dataForm = this.detail;
        this.executePlanData = JSON.parse(this.detail.executePlanData);
        this.detail.interfaces.forEach(function (item,idx) {
          that.interfaceData.push({
            "index": idx+1,
            "siaName": item.interfaceName
          })
          let tmpArr = [];
          item.assos.forEach(function (caseItem,caseIdx) {
            tmpArr.push({
              "index": caseIdx+1,
              "useCaseName": caseItem.testUseCase.remark,
              "id": caseItem.tucId
            });
          })
          that.useCaseList.push(tmpArr);
        })
        this.useCase = this.useCaseList[0];
        //console.log("executePlanData: ", this.executePlanData);
        //console.log("interfaceData: ", this.interfaceData);
      }
    },
    methods: {
      closeCall() {
        this.$emit("closeCall");
      },
      /**下一步**/
      next() {
        switch (this.activeIndex) {
          case 1:
            /*if (this.dataForm.name === "") {
              this.$message.error("测试任务名称");
              return;
            }
            let planForm = this.$refs.plan.getExecutePlanData();
            if (planForm.loopTime.length === 0 && this.$refs.plan.executeChecked) {
              this.$message.warning("请选择测试时间");
              return;
            }
            if(this.$refs.plan.executeChecked) {
              this.dataForm.startTime = new Date(planForm.loopTime[0]);
              this.dataForm.endTime = new Date(planForm.loopTime[1]);
              this.dataForm.executePlanData = JSON.stringify(planForm);
              this.dataForm.integrationTestTriggerParams = this.$refs.plan.createdData();
            }*/
            this.activeIndex = 3;
            break;
          case 2:
           /* if(this.interfaceData.length === 0) {
              this.$message.warning("至少要选择一个接口");
              return;
            }*/
            this.activeIndex = 3;
            break;
        }
      },
      /**选择服务列表回调**/
      serviceCall(sId) {
        this.sId = sId;
        this.isTestTools =  false;
        this.$nextTick(()=>{
          this.isTestTools = true;
        })
      },
      /**选择要测试的接口**/
      doDataShow(row){
        switch (row.fn) {
          case 1:
            let bool = false;
            for (let i = 0; i < this.interfaceData.length; i++) {
              if (this.interfaceData[i].siaId === row.data.siaId) {
                bool = true;
                break;
              }
            }
            if (bool) {
              this.$message.warning("已添加该接口了.");
              return;
            }
            this.interfaceData.push(row.data);
            break;
          case 2:
            this.isDetails = false;
            this.$nextTick(() => {
              this.isDetails = true;
              this.node = row.data;
            });
            break;
        }
      },
      /**点击接口行回调**/
      clickInterfaceCall(row) {
        this.useCase = this.useCaseList[parseInt(row.index)-1];
        this.axios.get("/api/center/interface?siaId="+row.index).then((rsp)=> {
          this.node = rsp.data;
          this.isInterfaceConfig = false;
          this.$nextTick(() => {
            this.isInterfaceConfig = true;
          });
        })
      },
      /**删除接口回调**/
      deleteCall(len, id) {
        if (len === 0) {
          this.activeIndex = 2;
          this.isInterfaceConfig = false;
        }
        else {
          /*if (this.node.siaId === id) {
            this.node = {};
            this.isInterfaceConfig = false;
          }*/
        }
      },
      /**批量删除用例**/
      /*deleteUseCase() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning("请选择测试用例.");
          return;
        }
        this.$confirm('您确定删除该用例吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.multipleSelection.forEach(item => {
            for (let i = 0; i < this.useCaseList.length; i++) {
              if (this.useCaseList[i].id === item.id) {
                this.useCaseList.splice(i, 1);
              }
            }
          })
        })
      },*/
      /**点击引用按钮**/
      onClickQuote(){
        if (!this.node) {
          this.$message.warning("请选择接口.");
          return;
        }
        this.isUseCase = false;
        this.$nextTick(()=>{
          this.isUseCase = true;
        })
      },
      /**勾选用例集合回调**/
      selectionChange(val) {
        this.multipleSelection = val;
      },
      /**点击用例列表行**/
      rowClickTestUse(row) {
        this.axios.get('/api/test/use/case/' + row.id)
          .then((res) => {
            this.node.updateInterfaceJson = JSON.parse(res.data.data.inBody);
            this.node.updateParamsJson = {
              inHeader: JSON.parse(res.data.data.inHeader),
              inQuery: JSON.parse(res.data.data.inQuery)
            };
            this.node.updateAssertJson = res.data.data.assertConditions;
            this.isInterfaceConfig = false;
            this.$nextTick(() => {
              this.isInterfaceConfig = true;
              this.disabled = true;
            })
            this.form = {
              useCaseName: res.data.data.useCaseName,
              remark: res.data.data.remark
            }
          })
      },
      /**点击删除用例列表按钮**/
      /*rowClickDelete(row) {
        this.$confirm('您确定删除该用例吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.useCaseList.forEach((item,index)=>{
            if (row.id === item.id) {
              this.useCaseList.splice(index, 1)
            }
          })
        })
      },*/
      /**引用回调**/
      useListCall(data){
        console.log(data);
        this.useCaseList = data.useList;
        this.interfaceData.forEach((item,index)=>{
          if(item.siaId == data.id) {
            this.interfaceData[index].useData = data.useList;
          }
        });
        this.isUseCase = false;
      },
      /**点击引用关闭弹出按钮**/
      closeCaseCall() {
        this.isUseCase = false;
      },
      /**获取选择接口用例数据结构**/
      getInterfaces(){
        let interfaces = [];
        this.interfaceData.forEach((item)=> {
          let interfacesItem = {
            assos: []
          };
          if (item.useData) {
            item.useData.forEach(i => {
              interfacesItem.assos.push({
                tucId: i.id
              })
            });
          }
          interfacesItem.interfaceId = item.siaId;
          interfacesItem.interfaceName = item.siaName;
          interfaces.push(interfacesItem);
        });
        return interfaces;
      },
      /**保存**/
      save() {
        this.dataForm.interfaces = this.getInterfaces();
        for (let i = 0; i < this.dataForm.interfaces.length; i++) {
          if (this.dataForm.interfaces[i].assos.length === 0) {
            this.$message.error("每个接口下面至少添加一个用例.");
            return;
          }
        }
        console.log(this.dataForm);
        this.axios.post("/api/integration/test", this.dataForm).then(res => {
          if (res.data.status === 0) {
            this.$message.success("添加成功.");
            this.$emit("closeCall");
          }
          else {
            this.$message.error(res.data.msg);
          }
        })
      }
    }
  }
</script>

<style>
  .el-step.is-simple .el-step__icon{top: 5px;}
  .el-dialog__body{background: #fff}
</style>
<style scoped lang="less">
  .body{
    height: 720px;
    padding: 15px;
    &-item{
      height: calc(100% - 60px);
    }
    .edit{
      border-radius: 6px;
      background: #f5f5f5;
      padding: 30px 50px 15px 15px;
      width: 60%;
      margin: 15px auto;
      overflow-y: auto
    }
    .title{
      font-size: 18px;
      color:#409eff;
      padding-bottom: 10px;
      font-weight: bold;
    }
    .border{
      border: 1px solid #e1e1e1;
      padding: 15px;
      height: 100%;
    }
    .border-item{
      border: 1px solid #e1e1e1;
      padding: 0 15px;
      margin-top: 15px;
    }
    .service-list-item{
      padding: 15px;
      .flex{
        display: flex;
        height: 100%;
        .flex-left{
          height: 100%;
          width: calc(100% - 300px);
        }
        .flex-right{
          height: 100%;
          width: 300px;
          padding-left: 15px;
          box-sizing: border-box;
        }
      }
    }
    .interface-bar{
      background: rgba(245, 245, 245, 1);
      padding-right: 15px;
      height: 100%;
      .interface-div{
        height: 100%;
        padding-top: 15px;
        background: #fff;
        padding-right: 15px;
      }
    }
    .use-case-bar{
      padding: 15px 15px 0 15px;
    }
    .interface-config-bar{
      height: 100%;
      background: rgba(245, 245, 245, 1);
      padding-left: 15px;
      box-sizing: border-box;
      .interface-config{
        height: 100%;
        padding: 15px;
        background: #fff;
        overflow-y: auto;
      }
    }
  }
  .api_info{padding: 5px 15px;
    span{color:#999;padding-left:10px;}
  }
  .btn-bar{
    text-align: center;
    padding: 15px;
  }
  .height{
    height: 100%;
  }

</style>
